package com.test.jdk.streamApi;

import com.test.jdk.funtionRel.Person;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class StreamTestReduce {
    public static void main(String[] args) {
        //定义一个list集合 对数据进行求和
        Integer reduce = Stream.of(4, 5, 3, 9)
                .reduce(0, (x, y) -> {
                    // 第一次的时候会将默认值赋值给x
                    // 之后每次会将 上一次的操作结果赋值给x y就是每次从数据中获取的元素
                    System.out.println("x=" + x + ",y=" + y);
                    return x + y;
                });
        System.out.println(reduce);

        //对数据集求最大值
        Integer max = Stream.of(4, 5, 3, 9)
                .reduce(0, (x, y) -> {
                    System.out.println("x=" + x + ",y=" + y);
                    return x > y ? x : y;
                });
        System.out.println(max);

        //reduch 与map 的组合使用
        //1.求出所有年龄的总和
        Integer sum = Stream.of(new Person(19, "张三"),
                new Person(20, "李四"),
                new Person(33, "汪汪"),
                new Person(22, "王五"))
                .map(Person::getAge) //获取年龄的Stream流
                .reduce(0, Integer::sum);
        System.out.println(sum);

        //求出所有年龄中的最大值
        Optional<Integer> max1 = Stream.of(new Person(19, "张三"),
                new Person(20, "李四"),
                new Person(33, "汪汪"),
                new Person(22, "王五"))
                .map(Person::getAge) //获取年龄的Stream流
                .max((o1, o2) -> o1 - o2);
        System.out.println(max1.get());

        //使用reduce的写法
        Integer ageMax = Stream.of(new Person(20, "李四"),
                new Person(33, "汪汪"),
                new Person(22, "王五"),
                new Person(19, "张三"))
                .map(Person::getAge).reduce(0, Math::max);
        System.out.println("person中年龄的最大值为：" + ageMax);

        //统计 字符 a 出现的次数
        Integer count = Stream.of("a", "b", "c", "d", "a", "c", "a")
                .map(msg->"a".equals(msg)? 1:0)//对流进行转换，进行判断统计数据
                .reduce(0,Integer::sum);
        System.out.println("字符 a 出现的次数:"+count);


    }


}
